package com.huxiu.yd.fragments;

import android.app.Activity;
import android.app.Fragment;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.PublishSpareActivity;
import com.huxiu.yd.R;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.Category;
import com.huxiu.yd.net.model.Province;
import com.huxiu.yd.net.model.Province.City;
import com.huxiu.yd.net.model.SpareItem;
import com.huxiu.yd.net.responses.CategoriesResponse;
import com.huxiu.yd.net.responses.SpareListResponse;
import com.huxiu.yd.utils.Settings;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.BusinessDistrictView;
import com.huxiu.yd.view.BusinessDistrictView.OnCitySelectedListener;
import com.huxiu.yd.view.SpareItemViewHolder;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by kHRYSTAL on 15/9/18:下午2:45.
 */
public class SpareFragment extends Fragment
        implements OnRefreshListener2<ListView>, OnClickListener, OnCitySelectedListener {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.area_button)
    TextView areaButton;

    @InjectView(R.id.area_layout)
    FrameLayout areaLayout;

    @InjectView(R.id.type_button)
    TextView typeButton;

    @InjectView(R.id.type_layout)
    FrameLayout typeLayout;

    @InjectView(R.id.person)
    TextView personButton;

    @InjectView(R.id.person_layout)
    FrameLayout personLayout;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    @InjectView(R.id.person_filter_all)
    TextView personFilterAll;

    @InjectView(R.id.person_filter_person)
    TextView personFilterPerson;

    @InjectView(R.id.person_filter_certificated)
    TextView personFilterCertificated;

    @InjectView(R.id.people_filter_container)
    LinearLayout personFilter;

    @InjectView(R.id.category_list)
    ListView categoryFilter;

    @InjectView(R.id.city_filter)
    BusinessDistrictView cityFilter;

    @InjectView(R.id.filter_container)
    LinearLayout filterContainer;

    @InjectView(R.id.top_divider)
    View topDivider;

    @InjectView(R.id.divider1)
    View divider1;

    private int selectedCategory = -1;

    private int selectedProvince = -1;

    private int selectedCity = -1;

    private int selectedPerson = -1;

    private List<Province> provinces = new ArrayList<>();

    private boolean isMine;

    private boolean isTopic;

    private boolean isAttention;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_spare, container, false);
        ButterKnife.inject(this, view);
        isMine = false;
        Bundle bundle = getArguments();
        if (bundle != null) {
            isMine = bundle.getBoolean("mine", false);
            isTopic = bundle.getBoolean("topic", false);
            isAttention = bundle.getBoolean("attention", false);
        }
        TextView emptyView = (TextView) view.findViewById(R.id.empty);
        list.setEmptyView(emptyView);
        if (isMine || isTopic || isAttention) {
            view.findViewById(R.id.header).setVisibility(View.GONE);
            filterContainer.setVisibility(View.GONE);
            topDivider.setVisibility(View.GONE);
            divider1.setVisibility(View.GONE);
            if (isMine && isTopic) {
                emptyView.setText(R.string.you_did_not_publish_any_spare);
            }
        } else {
            back.setVisibility(View.GONE);
            title.setText(R.string.spare);
            rightImage.setVisibility(View.GONE);
            rightText.setVisibility(View.VISIBLE);
            rightText.setText(R.string.publish);
            rightText.setTextColor(getResources().getColor(R.color.white));
            emptyView.setText(R.string.no_spare);
        }
        adapter = new SpareAdapter();
        list.setAdapter(adapter);
        list.setOnRefreshListener(this);
        list.setState(State.INIT_REFRESHING, true);
        areaLayout.setOnClickListener(this);
        provinces.addAll(Arrays.asList(Utils.getProvinces()));
        cityFilter.initData(provinces);
        cityFilter.setListener(this);
        typeLayout.setOnClickListener(this);
        personLayout.setOnClickListener(this);
        personFilterAll.setOnClickListener(this);
        personFilterPerson.setOnClickListener(this);
        personFilterCertificated.setOnClickListener(this);
        rightText.setOnClickListener(this);
        categoryAdapter = new CategoryAdapter();
        categoryFilter.setAdapter(categoryAdapter);
        categoryFilter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                selectedCategory = position;
                typeButton.setSelected(false);
                typeButton.setText(categories.get(position).name);
                switchViews();
                getItems(0);
            }
        });
        personButton.setText(R.string.no_limit);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }

    private SpareAdapter adapter;

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(currentPage + 1);
    }

    private void refreshComplete() {
        if (list != null)
            list.postDelayed(new Runnable() {
                @Override
                public void run() {
                    list.onRefreshComplete();
                }
            }, 100);
    }

    private int currentPage = 0;

    private void getItems(final int page) {
        String url = isMine || isAttention || isTopic ? NetworkConstants.MEMBER_URL : NetworkConstants.GOODS_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        String act = "lists";
        if (isMine || isAttention) {
            act = "my_favorite";
            params.put("opt", "user_goods");
        }
        if (isTopic) {
            act = "user_goods";
        }
        params.put("act", act);
        if (selectedProvince != -1) {
            Province province = provinces.get(selectedProvince);
            params.put("province_id", province.id);
            if (selectedCity != -1) {
                City city = province.city[selectedCity];
                if (!city.id.equals("-1")) {
                    params.put("city_id", city.id);
                }
            }
        }
        if (selectedPerson != -1 && selectedPerson != 0) {
            params.put("apply", Integer.toString(selectedPerson));
        }
        if (selectedCategory != -1) {
            params.put("category_id", categories.get(selectedCategory).id);
        }
        GsonRequest<SpareListResponse> request = new GsonRequest<>(url, Method.POST,
                SpareListResponse.class, true, params,
                new Listener<SpareListResponse>() {
                    @Override
                    public void onResponse(SpareListResponse response) {
                        getCategories();
                        if (response.isSuccess()) {
                            if (page == 0) {
                                items.clear();
                            }
                            Collections.addAll(items, response.data);
                            adapter.notifyDataSetChanged();
                            currentPage = response.page;
                        } else {
                            Utils.showToast(response.msg);
                        }
                        refreshComplete();
                    }
                }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Utils.showErrorMsg(volleyError);
                if (page == 0) {
                    items.clear();
                    adapter.notifyDataSetChanged();
                }
                refreshComplete();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private List<SpareItem> items = new ArrayList<>();

    private static final int REQUEST_PUBLISH_SPARE_ITEM = 0;

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.right_text:
                if (!Settings.isLoggedIn()) {
                    Utils.askLogIn(getActivity());
                    return;
                }
                Intent intent = new Intent(getActivity(), PublishSpareActivity.class);
                startActivityForResult(intent, REQUEST_PUBLISH_SPARE_ITEM);
                break;
            case R.id.area_layout:
                areaButton.setSelected(!areaButton.isSelected());
                if (areaButton.isSelected()) {
                    personButton.setSelected(false);
                    typeButton.setSelected(false);
                }
                switchViews();
                break;
            case R.id.person_layout:
                personButton.setSelected(!personButton.isSelected());
                if (personButton.isSelected()) {
                    areaButton.setSelected(false);
                    typeButton.setSelected(false);
                }
                switchViews();
                break;
            case R.id.type_layout:
                typeButton.setSelected(!typeButton.isSelected());
                if (typeButton.isSelected()) {
                    areaButton.setSelected(false);
                    personButton.setSelected(false);
                }
                switchViews();
                break;
            case R.id.person_filter_all:
                selectedPerson = 0;
                personButton.setSelected(false);
                personButton.setText(R.string.no_limit);
                switchViews();
                getItems(0);
                break;
            case R.id.person_filter_person:
                selectedPerson = 1;
                personButton.setSelected(false);
                personButton.setText(R.string.personal);
                switchViews();
                getItems(0);
                break;
            case R.id.person_filter_certificated:
                selectedPerson = 2;
                personButton.setSelected(false);
                personButton.setText(R.string.certificated);
                switchViews();
                getItems(0);
                break;
            default:
                break;
        }
    }

    private void switchViews() {
        cityFilter.setVisibility(areaButton.isSelected() ? View.VISIBLE : View.GONE);
        personFilter.setVisibility(personButton.isSelected() ? View.VISIBLE : View.GONE);
        categoryFilter.setVisibility(typeButton.isSelected() ? View.VISIBLE : View.GONE);
        if (personButton.isSelected()) {
            switch (selectedPerson) {
                case 0:
                    personFilterAll.setSelected(true);
                    personFilterPerson.setSelected(false);
                    personFilterCertificated.setSelected(false);
                    break;
                case 1:
                    personFilterAll.setSelected(false);
                    personFilterPerson.setSelected(true);
                    personFilterCertificated.setSelected(false);
                    break;
                case 2:
                    personFilterAll.setSelected(false);
                    personFilterPerson.setSelected(false);
                    personFilterCertificated.setSelected(true);
                    break;
                default:
                    personFilterAll.setSelected(false);
                    personFilterPerson.setSelected(false);
                    personFilterCertificated.setSelected(false);
                    break;
            }
        } else if (typeButton.isSelected()) {
            categoryAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != Activity.RESULT_OK) {
            return;
        }
        switch (requestCode) {
            case REQUEST_PUBLISH_SPARE_ITEM:
                break;
        }
    }

    @Override
    public void onCitySelected(int provinceIndex, int cityIndex, String cityName) {
        selectedProvince = provinceIndex;
        selectedCity = cityIndex;
        areaButton.setSelected(false);
        areaButton.setText(cityName);
        if (provinceIndex == 0 && cityIndex == 0)
            areaButton.setText(R.string.area);
        switchViews();
        getItems(0);
    }

    private class SpareAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public Object getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = convertView;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.spare_list_item, parent, false);
                SpareItemViewHolder holder = new SpareItemViewHolder(view, getActivity());
                holder.setAdapter(this);
                view.setTag(holder);
            }
            SpareItem item = items.get(position);
            SpareItemViewHolder holder = (SpareItemViewHolder) view.getTag();
            holder.bindItem(item, isMine, isAttention);
            return view;
        }

    }

    private List<Category> categories = new ArrayList<>();

    private void getCategories() {
        if (categories.size() > 0) {
            return;
        }
        String url = NetworkConstants.GOODS_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("act", "category");
        GsonRequest<CategoriesResponse> request = new GsonRequest<>(url, Method.POST,
                CategoriesResponse.class, false, params, new Listener<CategoriesResponse>() {
            @Override
            public void onResponse(CategoriesResponse response) {
                if (response.isSuccess()) {
                    categories.addAll(Arrays.asList(response.data));
                }
            }
        }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Utils.showToast(R.string.generic_failure);
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }

    private CategoryAdapter categoryAdapter;

    private class CategoryAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return categories.size();
        }

        @Override
        public Category getItem(int position) {
            return categories.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            TextView textView = (TextView) convertView;
            if (textView == null) {
                textView = (TextView) getActivity().getLayoutInflater()
                        .inflate(R.layout.category_filter_list_item, parent, false);
            }
            textView.setText(getItem(position).name);
            if (position == selectedCategory) {
                textView.setTextColor(getResources().getColor(R.color.button_green));
                textView.setBackgroundColor(getResources().getColor(R.color.white));
            } else {
                textView.setTextColor(getResources().getColor(R.color.gray5));
                textView.setBackgroundColor(getResources().getColor(R.color.gray1));
            }
            return textView;
        }
    }
}